<template>
  <div>
    <AuFormModal
      ref="formRef"
      v-model="showModal"
      :title="title"
      :formList="formList"
      :formData="selfFormData"
      :modalProps="{
        width: 700,
        height: '80vh',
        position: 'center'
      }"
      :formProps="{
        labelWidth: 100,
        class: '!w-[486px]'
      }"
      @handleConfirm="handleConfirm"
    >
      <template #logo_behind>
        <el-upload
          :show-file-list="false"
          class="upload-empDocs w-[24%]"
          action="/autata/file/upload"
          :data="{ foldername: 'material' }"
          accept="image/*"
          :before-upload="beforeUpload"
          @progress="onProgress"
          @success="e => onSuccess(e)"
          @error="onError"
        >
          <div v-loading="loading" class="w-full h-full">
            <img
              v-if="link"
              :src="handleImgURL(link) + link"
              class="h-full"
              alt=""
            />
            <div v-else class="text-center mt-[50%] translate-y-[-50%]">
              <FontIcon icon="icon-upload" />
            </div>
          </div>
        </el-upload>
        <span class="text-[--autata-font-gray-color]"
          >&emsp; {{ t("business_manage.modal.image_size") }}</span
        >
      </template>

      <template #operate_nature_behind>
        <el-radio-group v-model="operateRadio">
          <el-radio
            v-for="(item, index) in operateNatureList"
            :key="index"
            :label="item.value"
            >{{ t(item.label) }}
          </el-radio>
        </el-radio-group>
      </template>
    </AuFormModal>
  </div>
</template>

<script setup lang="ts">
import { computed, nextTick, ref, toRef, watch } from "vue";
import { AuFormModal } from "@/components/AuModal";
import { cloneDeep } from "lodash-unified";
import {
  businessAdd,
  businessGetList,
  BusinessListProps,
  businessUpdate
} from "@/api/factory/business";
import { FORM_LIST, operateNatureList } from "./constant";
import { getProvinceCity, ResultProps } from "@/api/user";
import {
  ElMessage,
  UploadFile,
  UploadFiles,
  UploadProgressEvent,
  UploadProps
} from "element-plus";
import { handleImgURL } from "@/utils/tool";
import { useI18n } from "vue-i18n";

const { t } = useI18n();

interface Props {
  modelValue: boolean;
  formData?: Partial<{}>;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false
});
const emit = defineEmits(["update:modelValue", "submit"]);

const title = ref("");
const link = ref(
  ""
  // "http://47.101.185.84:8088/uploadfile/autata/material/d03f32e2-4c1f-4156-ad5b-dc531d5c37dc.png"
);
const loading = ref(false);
const formList = ref([]);
const selfFormData: any = toRef(props, "formData");
const operateRadio = ref("连锁");
const provinceCity = ref([]);
const showModal = computed({
  get() {
    return props.modelValue;
  },
  set(val: boolean) {
    emit("update:modelValue", val);
  }
});

const surePwd = {
  type: "input",
  key: "surePassword",
  label: "business_manage.modal.confirm_password",
  required: true,
  placeholder: "business_manage.modal.confirm_password_placeholder",
  inType: "password",
  showPassword: true,
  rules: [
    {
      validator: (rule: any, value: string, callback: Function) => {
        const formData = formRef.value.getFormData();
        if (!value) {
          callback(
            new Error(t("business_manage.modal.confirm_password_required"))
          );
        } else if (formData.password !== value) {
          callback(
            new Error(t("business_manage.modal.confirm_password_mismatch"))
          );
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ]
};

const formRef = ref();

// region ====================================事件的集合
const beforeUpload: UploadProps["beforeUpload"] = rawFile => {
  if (!rawFile.type.includes("image")) {
    ElMessage.error(t("business_manage.modal.image_type_error"));
    return false;
  } else if (rawFile.size / 1024 / 1024 > 5) {
    ElMessage.error(t("business_manage.modal.image_size_error"));
    return false;
  }
  return true;
};

const onProgress = (
  event: UploadProgressEvent,
  file: UploadFile,
  uploadFiles: UploadFiles
) => {
  console.log(event);
  loading.value = true;
};

const onSuccess = (
  file: ResultProps<{
    relative_path: string;
    path: string;
    size: number;
  }>
) => {
  loading.value = false;
  const { data } = file;
  link.value = data.relative_path;
  formRef.value.setFormData({ logo: link.value });
};

const onError = (error: Error) => {
  console.log(error);
  ElMessage.error(t("business_manage.modal.upload_error"));
  loading.value = false;
};

const editDisabled = () => {};

const handleConfirm = () => {
  if (loading.value) {
    ElMessage.warning(t("business_manage.modal.uploading_warning"));
    return;
  }
  const data = cloneDeep(formRef.value.getFormData());
  let service = null;

  if (data.id) {
    service = businessUpdate;
  } else {
    service = businessAdd;
    data.country = "中国";
    data.is_notice = false;
    data.account_phone = data.phone;
  }
  data.hiddenDeviceType = true;
  data.logo = link.value;
  data.operate_nature = operateRadio.value;
  service(data).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: data.id
          ? t("business_manage.modal.edit_success")
          : t("business_manage.modal.add_success"),
        type: "success"
      });
      emit("update:modelValue", false);
      emit("submit");
    }
  });
};

const getCityList = (val: string) => {
  if (val) {
    const find = provinceCity.value.find(item => item.value === val);
    formRef.value.setFormProps("city", {
      options: find?.children ?? []
    });
  }
};

const businessSet = () => {
  businessGetList().then(res => {
    formRef.value.setFormProps("business_id", { options: res.data });
  });

  getProvinceCity().then(res => {
    provinceCity.value = res.data;
    formRef.value.setFormProps("province", {
      options: provinceCity.value
    });

    getCityList(selfFormData.value?.province);
  });
};

// endregion

watch(
  () => [showModal.value, props.formData],
  ([val, row]: [boolean, BusinessListProps]) => {
    if (val) {
      // debugger;
      title.value = row?.id
        ? t("business_manage.modal.edit_title")
        : t("business_manage.modal.add_title");
      const list = cloneDeep(FORM_LIST(t)).map(v => {
        if (v.key === "province") {
          v.onChange = (val: string) => {
            getCityList(val);
          };
        }
        return v;
      });
      formList.value = row?.id
        ? list.splice(0, list.length - 2)
        : list.concat(surePwd);
      // selfFormData.value = rowData;
      nextTick(async () => {
        formRef.value.setFormData(row);

        businessSet();
        link.value = row?.logo ?? "";
        formRef.value.setFormData({ logo: link.value });
        operateRadio.value = row?.operate_nature ?? "连锁";
        editDisabled();
      });
    } else {
      formRef.value.reset();
      link.value = "";
    }
  }
);
</script>
<style scoped lang="scss">
.upload-empDocs {
  position: relative;
  width: 80px;
  height: 80px;
  border-radius: 2px;

  &::before {
    position: absolute;
    inset: 0;
    pointer-events: none; /* 确保伪元素不会影响鼠标事件 */
    content: "";
    border: 2px dashed var(--autata-border-color);
    transition: border-color 0.3s ease; /* 平滑过渡边框颜色 */
  }

  &:hover::before {
    border-color: var(--el-color-primary);
  }

  :deep(.el-upload) {
    width: 100%;
    height: 100%;
    color: var(--el-color-primary);

    .iconfont {
      display: block;
      margin: 0 auto;
      font-size: 24px;
    }
  }
}
</style>
